/*
 * Copyright (c) 2012 Johan Fylling
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights 
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 * THE SOFTWARE.
 */

part of engine;


/**
 * A point in the [ContactManifold].
 */
class ContactPoint {
  final Vector2 position;
  final num     magnitude;
  
  ContactPoint (Vector2 position, num this.magnitude) : this.position = new Vector2.copy(position);
}

/**
 * Collection of [ContactPoint]s between two colliding objects.
 */
class ContactManifold {
  final Vector2 normal;
  final List<ContactPoint> points;
  
  ContactManifold (Vector2 normal) : this.normal = new Vector2.copy(normal),
                                     this.points = new List<ContactPoint>();
  
  /** Calculates the mean [ContactPoint] of the manifold. */
  ContactPoint get mean {
    if (this.points.isEmpty) {
      return null;
    }
    
    Vector2 positionSum = new Vector2();
    num magnitudeSum = 0.0;
    for (ContactPoint point in this.points) {
      positionSum += point.position;
      magnitudeSum += point.magnitude;
    }
    
    return new ContactPoint(positionSum / this.points.length, 
                            magnitudeSum / this.points.length);
  }
  
  /** Returnes the deepest [ContactPoint] in the manifold. */
  ContactPoint get deepest {
    if (this.points.isEmpty) {
      return null;
    }
    
    ContactPoint selected = null;
    for (ContactPoint point in this.points) {
      if (selected == null || point.magnitude > selected.magnitude) {
        selected = point;
      }
    }
    
    return selected;
  }
}
